import 'package:dio/dio.dart';
import 'package:dotted_decoration/dotted_decoration.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
// import 'package:puppy_store/models/cart_model.dart';
import 'package:puppy_store/models/goods_detail_model.dart';
import 'package:puppy_store/models/order_payment_model.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_bottom_bar.dart';
import 'package:puppy_store/pages/order_payment/order_settlement_page.dart';
import 'package:puppy_store/service/cart_api.dart';
import 'package:puppy_store/service/order_payment.dart';
import 'package:puppy_store/utils/powerset.dart';
import 'package:puppy_store/widgets/custom_image.dart';
import 'package:puppy_store/widgets/price_widget.dart';
import 'package:flutter/material.dart';

// 区分商品规格弹窗不同入口
enum SpecsActionType {
  normal, // 点击"请选择规格", 展示"加入购物车" 和 "立即购买"
  addCart, // 点击"加入购物车", 展示"请选择规格"
  buyNow, // 点击"立即购买", 展示"请选择规格"
}

class GoodsSpecsWidget extends StatefulWidget {
  const GoodsSpecsWidget({
    this.specsStrCallback,
    this.goodsDetailModel,
    this.type,
    super.key,
  });

  /// 商品详情总模型
  final GoodsDetailModel? goodsDetailModel;

  // 回调规格字符串回调函数
  final void Function(String? showSpecsStr)? specsStrCallback;

  // 记录商品规格弹窗入口类型
  final SpecsActionType? type;

  @override
  State<GoodsSpecsWidget> createState() => _GoodsSpecsWidgetState();
}

class _GoodsSpecsWidgetState extends State<GoodsSpecsWidget> {
  /// 未选中状态
  final BoxDecoration _unselectedDecoration = BoxDecoration(
    color: Color(0xFFF6F6F6),
    border: Border.all(color: Color(0xFFF6F6F6), width: 0.5),
    borderRadius: BorderRadius.circular(13.0),
  );

  /// 未选中文字颜色
  final Color _unselectedTextColor = Color(0xFF333333);

  /// 选中状态
  final BoxDecoration _selectedDecoration = BoxDecoration(
    color: Colors.white,
    border: Border.all(color: Color(0xFFCF4444), width: 0.5),
    borderRadius: BorderRadius.circular(13.0),
  );

  /// 选中文字颜色
  final Color _selectedTextColor = Color(0xFFCF4444);

  /// 禁用状态 , flutter中没有提供虚线变宽的款式, 所以需要使用第三方库
  final DottedDecoration _disableDecoration = DottedDecoration(
    shape: Shape.box,
    color: Color(0xFFCBCBCB),
    strokeWidth: 0.5,
    borderRadius: BorderRadius.circular(13.0),
  );

  /// 禁用文字颜色
  Color _disableTextColor = Color(0xFFCBCBCB);

  /// 记录商品数量
  int _skuCount = 1;

  // 记录已选的规则路径
  List<String>? _selectedSpecsValues;

  // 记录规格路径字典
  Map _specsPathMap = {};

  // 选中规格的SKU
  GoodsSkusModel? _selectedSku;

  // 已选规格字符
  String? _selectedSpecsStr;

  // 完全选中后的规格
  String? _showSpecsStr;

  // 初始化
  @override
  void initState() {
    // 生成规格路径字典
    _specsPathMap = _getSpecsPath(widget.goodsDetailModel!.skus!);

    // 默认先做一次匹配,保证那些没有库存的规格组合默认被禁用
    _matchSpecsPath(widget.goodsDetailModel!.specs!);

    super.initState();
  }

  // 生成规格路径字典
  Map _getSpecsPath(List<GoodsSkusModel> skus) {
    Map pathMap = {};
    // 1. 遍历skus, 取出有库存的SKU
    skus.forEach((GoodsSkusModel sku) {
      List skuSpecs = [];
      if (sku.inventory! > 0) {
        // //2. 取出有库存的SKU的规格,存到List中
        sku.specs!.forEach((GoodsSkusSpecsModel skuSpecsModel) {
          skuSpecs.add(skuSpecsModel.valueName!);
        });
        debugPrint('有库存的SKU规格: $skuSpecs');
        // 计算有库存的规格幂集: 幂集算法库PowerSet
        List<List> skuSpecsPowerset = powerset(skuSpecs).toList();
        debugPrint('有库存的SKU规格幂集: $skuSpecsPowerset');

        // 3. 生成有库存的规格路径字典
        skuSpecsPowerset.forEach((List subSet) {
          if (subSet.isNotEmpty) {
            // 将规格组合转成字典的key
            String key = subSet.join('*');
            if (pathMap.containsKey(key)) {
              pathMap[key].add(sku);
            } else {
              pathMap[key] = [sku];
            }
          }
        });
      }
    });
    debugPrint('有库存的规格路径字典: $pathMap');
    return pathMap;
  }

  //   匹配规则路径
  void _matchSpecsPath(List<GoodsSpecsModel> specs) {
    // 准备存放选中规格的列表 元素的长度是规格类型的个数
    // List.filled(length, default, growable) 生成固定长度的数组 growable为false时,当第一次追加值时,后面的元素都被追加为同样的值
    // growable为true时,后面的元素可以追加不同的值
    _selectedSpecsValues = List.filled(specs.length, '', growable: true);

    // 获取已选中的规格
    for (var i = 0; i < specs.length; i++) {
      GoodsSpecsModel specsModel = specs[i];
      // 遍历规格值, 找到选中的规格值
      specsModel.values!.forEach((GoodsSpecsValues specsValue) {
        if (specsValue.selected) {
          // 将选中状态的值存储到List中
          _selectedSpecsValues![i] = specsValue.name!;
        }
      });
    }

    // debugPrint('已选中的规格: $_selectedSpecsValues');

    // 遍历所有规格
    for (var i = 0; i < specs.length; i++) {
      GoodsSpecsModel specsModel = specs[i];
      specsModel.values!.forEach((GoodsSpecsValues specsValue) {
        // 复制一份已选择规格列表,未了避免将来在生成规格路径key由于操作数据影响_selectedSpecsValues
        List<String> selectedSpecsValuesTmp = List.from(_selectedSpecsValues!);
        // 注意点: 已选的规格不需要组合
        if (selectedSpecsValuesTmp.contains(specsValue.name!)) {
          return;
        }
        // 使用已选的规格跟遍历出来的规格进行组合
        selectedSpecsValuesTmp[i] = specsValue.name!;

        debugPrint('当前要匹配规则的组合: $_selectedSpecsValues');

        // 生成规格路径key, ['蓝色', 30cm, ''] =  '蓝色*30cm'
        // 先去除空字符串
        selectedSpecsValuesTmp.removeWhere((element) => element == '');
        String selectedKey = selectedSpecsValuesTmp.join('*');
        debugPrint('当前要匹配规则选中的key: $selectedKey');

        // 匹配规格路径字典
        specsValue.disabled = !_specsPathMap.containsKey(selectedKey);
      });
    }

    // 展示选中的SKU信息
    // 获取选中的SKU
    // 判断所有类型的规格是否选择齐全
    if (!_selectedSpecsValues!.contains('')) {
      String key = _selectedSpecsValues!.join('*');
      _selectedSku = _specsPathMap[key][0];
      debugPrint('选中的SKU: ${_selectedSku?.id}');

      // 规格选择齐全: 生成规格字符串
      _showSpecsStr = _selectedSpecsValues!.join('');
    } else {
      _showSpecsStr = null;
    }

    // 如果没有选择任何规格,则_selectedSku = null
    if (_selectedSpecsValues!.every((element) => element == '')) {
      _selectedSku = null;
    }

    // 展示已选规格文字描述
    List selectedSpecsValuesTmp = List.from(_selectedSpecsValues!);
    selectedSpecsValuesTmp.removeWhere((element) => element == '');
    _selectedSpecsStr = selectedSpecsValuesTmp.join(' ');
    if (_selectedSpecsStr!.isNotEmpty) {
      _selectedSpecsStr = '已选: $_selectedSpecsStr';
    } else {
      _selectedSpecsStr = '请选择规格';
    }
  }

  // 根据规格状态,读取选中,未选中,禁用状态
  dynamic _getDecoration(GoodsSpecsValues specsValue) {
    if (specsValue.disabled) return _disableDecoration;
    if (specsValue.selected) return _selectedDecoration;
    return _unselectedDecoration;
  }

  // 根据规格状态,读取选中,未选中,禁用文字状态颜色
  Color _getTextColor(GoodsSpecsValues specsValue) {
    if (specsValue.disabled) return _disableTextColor;
    if (specsValue.selected) return _selectedTextColor;
    return _unselectedTextColor;
  }

  // 底部操作栏点击事件
  void _bottomBarOnTap(SpecsActionType type) async {
    // 校验规格
    for (var i = 0; i < _selectedSpecsValues!.length; i++) {
      String specs = _selectedSpecsValues![i];
      if (specs == '') {
        // 弹出提示
        EasyLoading.showToast('请选择${widget.goodsDetailModel!.specs![i].name}');
        return;
      }
    }

    switch (type) {
      case SpecsActionType.addCart:
        try {
          Map res = await CartApi.addCart(_selectedSku!.id!, _skuCount);
          // 跨组件通信 步骤4: 在要更新的地方 通知ValueNotifier更新值, 局部刷新界面
          totalCountNotifier!.value += _skuCount;
          // 关闭弹窗
          Navigator.of(context, rootNavigator: true).pop();
          EasyLoading.showToast("添加购物车成功");
        } on DioException catch (e) {
          EasyLoading.showToast("添加购物车异常: ${e.response?.data['message']}");
        }
        break;
      case SpecsActionType.buyNow:
        // 立即购买
        // debugPrint('立即购买');
        try {
          OrderSettlementModel settlementModel =
              await OrderPaymentAPI.orderBuyNow(_selectedSku!.id!, _skuCount);

          //关闭弹窗
          Navigator.of(context, rootNavigator: true).pop();

          Navigator.push(
            context,
            CupertinoPageRoute(
              builder: (BuildContext context) {
                return OrderSettlementPage(
                  orderSettlementModel: settlementModel,
                );
              },
            ),
          );

          // debugPrint('立即购买成功: $orderSettlementModel');
        } on DioException catch (e) {
          EasyLoading.showToast("立即购买异常: ${e.response?.data['message']}");
        }
        break;
      default:
        break;
    }
  }

  // 监听组件即将销毁时的生命周期方法
  @override
  void deactivate() {
    // 当页面销毁时, 重置状态
    // _skuCount = 1;
    // _selectedSpecsValues = [];
    // _selectedSku = null;
    // _selectedSpecsStr = '请选择规格';
    if (widget.specsStrCallback != null) {
      widget.specsStrCallback!(_showSpecsStr);
    }
    super.deactivate();
  }

  /// 构建上平规格显示项
  List<Widget> _buildGoodsSpecs(List<GoodsSpecsModel> specs) {
    List<Widget> items = [];

    // 遍历Specs, 并且纵向布局商品的规格名称 及 值
    for (var i = 0; i < specs.length; i++) {
      items.add(
        Padding(
          padding: EdgeInsets.only(bottom: 10.0),
          child: Container(
            // height: 40.0,
            width: MediaQuery.of(context).size.width,
            color: Colors.white,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  specs[i].name!,
                  style: TextStyle(fontSize: 14.0, color: Color(0xFF333333)),
                ),
                Padding(padding: EdgeInsets.only(top: 10.0)),
                Wrap(
                  spacing: 10.0, // 元素间的间距
                  runSpacing: 14.0, // 行之间的间距,
                  children: _buildGoodsSpecsValues(specs[i].values!),
                ),
              ],
            ),
          ),
        ),
      );
    }
    return items;
  }

  // 构建商品规格值
  List<Widget> _buildGoodsSpecsValues(List<GoodsSpecsValues> specsValue) {
    List<Widget> items = [];
    // 遍历SpecsValue, 并且纵向布局商品的规格名称 及 值
    for (var i = 0; i < specsValue.length; i++) {
      items.add(
        GestureDetector(
          onTap: () {
            // 禁用状态的规格不响应点击事件
            if (specsValue[i].disabled) return;

            debugPrint('点击了${specsValue[i].name}');
            // 遍历规格
            specsValue.forEach((element) {
              // 如果被点击规格未选中， 则选中该规格， 其他规格不选中
              //如果被点击规格已选中， 则取消选中该规格， 其他规格不选中
              if (element.name == specsValue[i].name) {
                element.selected = !specsValue[i].selected;
              } else {
                element.selected = false;
              }
            });

            // 匹配规则路径
            _matchSpecsPath(widget.goodsDetailModel!.specs!);

            // 更新状态
            setState(() {});
          },
          child: Container(
            padding: EdgeInsets.only(left: 10.0, right: 10.0),
            decoration: _getDecoration(specsValue[i]),
            child: Text(
              specsValue[i].name!,
              style: TextStyle(
                color: _getTextColor(specsValue[i]),
                fontSize: 14.0,
                // 中文字符和英文字符在flutter中的默认行高是不一样的, 所以需要设置行高
                height: 2.0,
              ),
            ),
          ),
        ),
      );
    }
    return items;
  }

  /// 底部操作栏
  Widget _buildBottomBar() {
    if (widget.type == SpecsActionType.addCart ||
        widget.type == SpecsActionType.buyNow) {
      return GestureDetector(
        onTap: () {
          _bottomBarOnTap(widget.type!);
        },
        child: Container(
          height: 40.0,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4.0),
            gradient: LinearGradient(
              colors: [Color(0xFF00D2AE), Color(0xFF00BD9A)],
            ),
          ),
          child: Text(
            '确定',
            style: TextStyle(color: Colors.white, fontSize: 14.0),
          ),
        ),
      );
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: GestureDetector(
            onTap: () {
              _bottomBarOnTap(SpecsActionType.addCart);
            },
            child: Container(
              height: 40.0,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(2.0),
                gradient: LinearGradient(
                  colors: [Color(0xffFFA868), Color(0xffFF9240)],
                ),
              ),
              child: Text(
                '加入购物车',
                style: TextStyle(fontSize: 13.0, color: Colors.white),
              ),
            ),
          ),
        ),
        SizedBox(width: 20.0),
        Expanded(
          child: GestureDetector(
            onTap: () {
              _bottomBarOnTap(SpecsActionType.buyNow);
            },
            child: Container(
              height: 40.0,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(2.0),
                gradient: LinearGradient(
                  colors: [Color(0xff3CCEAF), Color(0xff27BA9B)],
                ),
              ),
              child: Text(
                '立即购买',
                style: TextStyle(fontSize: 13.0, color: Colors.white),
              ),
            ),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height * 0.7,
      color: Colors.white,
      child: Stack(
        children: [
          Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  child: Container(
                    padding: EdgeInsets.only(
                      left: 10.0,
                      top: 18.0,
                      right: 10.0,
                    ),
                    child: Column(
                      children: [
                        // 商品信息
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            // 图片
                            CustomImage(
                              url: widget.goodsDetailModel!.mainPictures![0],
                              width: 100.0,
                              height: 100.0,
                            ),
                            // 价格 + 已选规格属性
                            Expanded(
                              child: Padding(
                                padding: EdgeInsets.only(left: 10.0),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    // 现价和原价
                                    Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.end,
                                      children: [
                                        // 现价
                                        PriceWidget(
                                          price:
                                              _selectedSku != null
                                                  ? _selectedSku!.price!
                                                  : widget
                                                      .goodsDetailModel!
                                                      .price!,
                                          symbolFontSize: 12.0,
                                          integerFontSize: 20.0,
                                          decimalFontSize: 14.0,
                                        ),
                                        // 原价
                                        Padding(
                                          padding: EdgeInsets.only(left: 6.0),
                                          child: Text(
                                            '¥${_selectedSku != null ? _selectedSku!.oldPrice! : widget.goodsDetailModel!.oldPrice!}',
                                            style: TextStyle(
                                              fontSize: 12.0,
                                              color: Color(0xFF555555),
                                              decoration:
                                                  TextDecoration.lineThrough,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                    // 已选规格属性
                                    Padding(
                                      padding: EdgeInsets.only(top: 6.0),
                                      child: Text(
                                        _selectedSpecsStr!,
                                        style: TextStyle(
                                          fontSize: 12.0,
                                          color: Color(0xFF555555),
                                        ),
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        // 规格信息
                        Padding(
                          padding: EdgeInsets.only(top: 20.0),
                          child: Container(
                            width: MediaQuery.of(context).size.width,
                            padding: EdgeInsets.only(left: 6, right: 6),
                            child: Column(
                              children: _buildGoodsSpecs(
                                widget.goodsDetailModel!.specs!,
                              ),
                            ),
                          ),
                        ),
                        // 商品数量
                        Padding(
                          padding: EdgeInsets.only(top: 20.0, bottom: 30.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '数量',
                                style: TextStyle(
                                  color: Color(0xFF333333),
                                  fontSize: 14.0,
                                ),
                              ),
                              Row(
                                children: [
                                  IconButton(
                                    onPressed: () {
                                      if (_skuCount <= 1) return;
                                      setState(() {
                                        _skuCount--;
                                      });
                                    },
                                    icon: Image.asset(
                                      _skuCount != 1
                                          ? 'assets/price_jian_on.png'
                                          : 'assets/price_jian.png',
                                    ),
                                  ),
                                  Container(
                                    width: 40.0,
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.symmetric(
                                      vertical: 1.0,
                                    ),
                                    color: Color(0xFFF6F6F6),
                                    child: Text(
                                      _skuCount.toString(),
                                      style: TextStyle(
                                        color: Color(0xFF333333),
                                        fontSize: 14.0,
                                      ),
                                    ),
                                  ),
                                  IconButton(
                                    onPressed: () {
                                      setState(() {
                                        _skuCount++;
                                      });
                                    },
                                    icon: Image.asset(
                                      'assets/price_jia_on.png',
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              // 底部操作栏
              Container(
                height: 60.0 + MediaQuery.of(context).padding.bottom,
                child: Column(
                  children: [
                    Divider(height: 1.0, color: Color(0xFFEDEDED)),
                    Container(
                      padding: EdgeInsets.only(left: 20.0, right: 20.0),
                      child: Padding(
                        padding: EdgeInsets.only(top: 9.0),
                        child: _buildBottomBar(),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          // 关闭按钮
          Positioned(
            top: 0.0,
            right: 0.0,
            child: IconButton(
              icon: Image.asset('assets/guanbi.png'),
              onPressed: () {
                // 关闭弹窗

                Navigator.of(context, rootNavigator: true).pop();
              },
            ),
          ),
        ],
      ),
    );
  }
}
